<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="130px">
      <el-form-item label="课程学期" prop="term">
        <el-select v-model="queryParams.term" placeholder="请选择课程学期" clearable style="width: 200px">
          <el-option
            v-for="dict in course_term"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
        <el-form-item label="老师选择" prop="userId">
            <el-select v-model="queryParams.userId" placeholder="请选择老师" style="width: 200px" >
                <el-option
                        v-for="teacher in teachers"
                        :key="teacher.userId"
                        :label="teacher.userName"
                        :value="teacher.userId"

                />
            </el-select>
        </el-form-item>

      <el-form-item style="margin-left: 45px">
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
      <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-row :gutter="10" class="mb8">
        <el-link type="primary">选课信息</el-link>
    </el-row>


    <div style="border: #006eb9 solid 1px;border-radius: 10px;">
        <el-table v-loading="loading" :data="studentCourseList" @selection-change="handleSelectionChange">
            <!--      <el-table-column type="selection" width="55" align="center" />-->
            <!--        id，但是不展示-->
            <div style="display: none">
                <el-table-column label="id" align="center" prop="id" />
            </div>
            <el-table-column label="课程名称" align="center" prop="name" />
            <el-table-column label="课程学期" align="center" prop="term">
                <template #default="scope">
                    <dict-tag :options="course_term" :value="scope.row.term"/>
                </template>
            </el-table-column>
            <!--        userId-->
            <div style="display: none">
                <el-table-column label="userId" align="center" prop="userId" />
            </div>
            <el-table-column label="老师" align="center" prop="teacher.userName" />
            <el-table-column label="当前人数 / 最大人数" align="center">
                <template #default="{ row }">
                    {{ row.nownum }}/{{ row.maxnum }}
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
                <template #default="scope" >
                    <el-button
                            v-if="!scope.row.selected"
                            link
                            type="primary"
                            icon="Edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['studentCourse:studentCourse:edit']"
                            :disabled="scope.row.selected"
                    >选课</el-button>
                    <el-button link
                               type="secondary"
                               disabled v-else><el-icon><CircleCheck /></el-icon>&nbsp;已选</el-button>
                    <el-button
                            v-if="scope.row.selected"
                            link
                            type="primary"
                            icon="ArrowLeft"
                            @click="handledeUpdate(scope.row)"
                            v-hasPermi="['studentCourse:studentCourse:edit']">
                        退课
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

    </div>
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改我要选课对话框 -->
<!--    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="studentCourseRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="学时" prop="hours">
          <el-input v-model="form.hours" placeholder="请输入学时" />
        </el-form-item>
        <el-form-item label="学分" prop="credits">
          <el-input v-model="form.credits" placeholder="请输入学分" />
        </el-form-item>
        <el-form-item label="课程学期" prop="term">
          <el-select v-model="form.term" placeholder="请选择课程学期">
            <el-option
              v-for="dict in course_term"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课时安排" prop="arrangement">
          <el-select v-model="form.arrangement" placeholder="请选择课时安排">
            <el-option
              v-for="dict in course_arrangement"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述" prop="coursedesc">
          <el-input v-model="form.coursedesc" placeholder="请输入课程描述" />
        </el-form-item>
        <el-form-item label="教室" prop="classroom">
          <el-input v-model="form.classroom" placeholder="请输入教室" />
        </el-form-item>
        <el-form-item label="人数" prop="maxnum">
          <el-input v-model="form.maxnum" placeholder="请输入人数" />
        </el-form-item>
        <el-form-item label="图片" prop="imgs">
          <image-upload v-model="form.imgs"/>
        </el-form-item>
        <el-form-item label="开始日期" prop="starttime">
          <el-date-picker clearable
            v-model="form.starttime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endtime">
          <el-date-picker clearable
            v-model="form.endtime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="星期" prop="courseweek">
          <el-select v-model="form.courseweek" placeholder="请选择星期">
            <el-option
              v-for="dict in user_week"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户编号" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户编号" />
        </el-form-item>
        <el-form-item label="老师编号" prop="teacherId">
          <el-input v-model="form.teacherId" placeholder="请输入老师编号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>-->
  </div>
</template>

<script setup name="StudentCourse">
import {listTeacher, listStudentCourse, getStudentCourse, delStudentCourse, addStudentCourse, updateStudentCourse,deUpdateStudentCourse } from "@/api/studentCourse/studentCourse";
// import { listTeacher } from "@/api/course/course"
import {onMounted, ref} from "vue";
import { ElMessage,ElMessageBox } from 'element-plus';
const { proxy } = getCurrentInstance();
const { course_arrangement, course_term, user_week } = proxy.useDict('course_arrangement', 'course_term', 'user_week');

const studentCourseList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");


const teachers = ref([]);

onMounted(() => {
    loadTeachers();
});

// 查询所有老师
const loadTeachers = async () => {
    try {
        const response = await listTeacher();
        teachers.value = response.data || []; // 假设response.data是包含老师列表的数组
    } catch (error) {
        console.error('Error fetching teachers:', error);
    }
};


const data = reactive({
  form: {
      userId:localStorage.getItem('userId'),
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    term: null,
    arrangement: null,
    coursedesc: null,
    classroom: null,
    maxnum: null,
    nownum:null,
    imgs: null,
    starttime: null,
    endtime: null,
    courseweek: null,
    userId: null,
      teacher: {
          userId: null,
          userName: null
      }
  },
  rules: {
    name: [
      { required: true, message: "课程名称不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询我要选课列表 */
const getList = () => {
    listStudentCourse(queryParams.value).then(response => {
        studentCourseList.value = response.rows.map(row => ({
            ...row,
            // 初始化时，根据Map中的状态设置selected属性
            selected: selectedStatuses.value.get(row.id) || false,
        }));
    });
};
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    hours: null,
    credits: null,
    term: null,
    arrangement: null,
    coursedesc: null,
    classroom: null,
    maxnum: null,
    nownum:null,
    imgs: null,
    starttime: null,
    endtime: null,
    courseweek: null,
    userId: null,
      teacher: {
          userId: null,
          userName: null
      }
  };
  proxy.resetForm("studentCourseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}




const selectedStatuses = ref(new Map());
/** 选课按钮操作 */
const handleUpdate = async (row) => {

        // 设置selected状态为true，即使后续失败也不再允许选课
        selectedStatuses.value.set(row.id, true);

        const payload = {
            //必须要传递,学生编号,要往student_course插入userId
            userId: localStorage.getItem('userId'),
            id: row.id,
            maxnum: row.maxnum,
            nownum: row.nownum,
        };

        const result = await updateStudentCourse(payload);
        if (result === -1) {
            ElMessage.error('选课失败，您已选过该课程！');
        } else {
            ElMessage.success('选课成功');
            await getList();
        }

};

/** 退课按钮操作 */
const handledeUpdate = async (row) => {
    try {
        // 显示确认对话框
        const confirmResult = await ElMessageBox.confirm(
            '确定要退课吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        if (confirmResult === 'confirm') {
            // 用户点击了确定按钮，准备退课请求的payload
            const payload = {
                userId: localStorage.getItem('userId'),
                id: row.id,
                // 如果需要，可以添加更多字段
            };

            // 发送退课请求
            const result = await deUpdateStudentCourse(payload);

            if (result) {
                ElMessage.success('退课成功');
                // 重置selected状态
                selectedStatuses.value.set(row.id, false);
                // 重新加载列表以反映最新的选课状态
                await getList();
            } else {
                ElMessage.error('退课失败');
            }
        } else {
            // 用户点击了取消按钮，不做任何操作
            ElMessage.info('已取消退课');
        }
    } catch (error) {
        ElMessage.error('退课失败');
        console.error(error);
    }
};

/** 提交按钮 */
function submitForm() {
  proxy.$refs["studentCourseRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateStudentCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("选课成功");
          // open.value = false;
          getList();
        });
      } else {
        addStudentCourse(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}




getList();
</script>
<style scoped>
    .el-link {
        font-size: 26px;
        margin: 0 auto;
        text-align: center;
        margin-bottom: 8px;
    }
    .el-link .el-icon--right.el-icon {
        vertical-align: text-bottom;

    }
    .el-table{
        width: 95%;
        border-radius: 10px;
        margin: 40px;
    }
</style>
